from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate, login
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from django.middleware.csrf import get_token

# class GetCSRFTokenView(APIView):
#     def get(self, request):
#         # 会设置csrftoken cookie
#         token = get_token(request)
#         return Response({"csrfToekn": token})
# # 在登陆接口添加csrf认证
# @method_decorator(csrf_protect, name="dispatch")
# class LoginView(APIView):
#     # 登陆不需要认证和权限
    
#     def post(self, request):
#         username = request.data.get('username')
#         password = request.data.get('password')

#         # 验证用户名和密码
#         # authenticate是Django提供的验证用户身份的方法
#         user = authenticate(request, username=username, password=password)

#         # 判断用户是否存在
#         if user is not None:
#             # login()方法是Django提供的登录用户的方法
#             login(request, user)
#             return Response({"message": "登陆成功"}, status=status.HTTP_200_OK)
#         else:
#             return Response({"message": "用户名或密码错误"}, status=status.HTTP_401_UNAUTHORIZED)

# from rest_framework.authtoken.models import Token
# class TokenLoginView(APIView):
#     def post(self, request):
#         username = request.data.get('username')
#         password = request.data.get('password')
#         # 验证用户名和密码
#         # authenticate是Django提供的验证用户身份的方法
#         user = authenticate(request, username=username, password=password)
#         # 判断用户是否存在

#         if user:
#             # 生成token
#             # Token.objects.get_or_create 方法是Django提供的生成token的方法
#             # 第一个参数是user对象
#             token, created = Token.objects.get_or_create(user=user) 
            
#             return Response({"token": token.key}, status=status.HTTP_200_OK)
#         else:
#             return Response({"message": "用户名或密码错误"}, status=status.HTTP_401_UNAUTHORIZED)
    